package com.xx.springboot.config.shiro;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * @author  xiaoxi
 * @description: 对没有登录的信息进行拦截, 重写FormAuthenticationFilter方法, 将原本的重定向到login.jsp 现在以返回json的方式提示
 */
public class LoginPermissionAuthorzationFilter extends FormAuthenticationFilter {


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        JSONObject json = new JSONObject();
        json.put("stats", "1001");
        json.put("message", "还未登录, 请先登录!");
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json");
        res.getWriter().write(JSONObject.toJSON(json).toString());
        return false;
    }

    @Bean
    public FilterRegistrationBean registration(LoginPermissionAuthorzationFilter filter){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(filter);
        filterRegistrationBean.setEnabled(true);
        return filterRegistrationBean;
    }
}
